import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:furaha_mkopo/cache/fm_cache_tool.dart';
import 'package:furaha_mkopo/commonTool/fm_language_tool.dart';
import 'package:furaha_mkopo/net/fm_http_response.dart';
import 'package:furaha_mkopo/page/dialog/address/entity/fm_address_entity.dart';
import 'package:furaha_mkopo/page/dialog/address/enum/fm_select_address_enum.dart';
import 'package:furaha_mkopo/page/dialog/address/fm_address_api.dart';
import 'package:get/get.dart';

class FMSelectAddressPage extends StatefulWidget {
  String levelAddress1;
  String levelAddress2;
  Function(String addressValue) callBack;
  FMSelectAddressPage({super.key,required this.levelAddress1,required this.levelAddress2,required this.callBack});

  @override
  State<FMSelectAddressPage> createState() => _FMSelectAddressPageState();

  static void showAddress(String address,Function(String addressValue) callBack){
    List<String> addressList = address.split("|");
    if(addressList.isEmpty){
      addressList = ["",""];
    }else if(addressList.length == 1){
      addressList.add("");
    }
    Get.to(FMSelectAddressPage(
      levelAddress1: addressList[0],
      levelAddress2: addressList[1],
      callBack: callBack,
    ),opaque: false,duration: const Duration(milliseconds: 0));
  }
}

class _FMSelectAddressPageState extends State<FMSelectAddressPage> {
  FMSelectAddressEnum _selectAddressEnum = FMSelectAddressEnum.level1;
  String testJson = FMCacheTool.getAddressList();
  List<FMAddressMySelfEntity> level1 = [];
  Map<String, List<FMAddressMySelfEntity>> level2 = {};
  Map<String, List<FMAddressMySelfEntity>> level3 = {};
  String get level1Select => widget.levelAddress1;
  set level1Select(String value){
    widget.levelAddress1 = value;
  }
  String get level2Select => widget.levelAddress2;
  set level2Select(String value){
    widget.levelAddress2 = value;
  }

  @override
  void initState() {
    super.initState();
    initTestData();
  }

  void initTestData() async {
    if(testJson == "[]" || testJson.isEmpty){
      FMAddressApi addressApi = FMAddressApi();
      FMHttpResponse<dynamic> response = await addressApi.send();
      if(response.data != null){
        testJson = response.data;
      }
    }
    final List<dynamic> mapList = jsonDecode(testJson);

// 使用更明确的变量命名
    level1 = mapList.map((provinceJson) {
      final province = FMAddressMySelfEntity.json(provinceJson);

      // 处理二级地址
      final List<FMAddressMySelfEntity> cities = province.myself ?? [];
      if (province.planned != null) {
        level2[province.planned!] = cities;
      }

      // 处理三级地址（提取为独立方法）
      void processChildren(FMAddressMySelfEntity city) {
        final districts = city.myself ?? [];
        if (city.planned != null) {
          level3[city.planned!] = districts;
        }
      }

      cities.where((c) => c.planned != null).forEach(processChildren);
      return province;
    }).toList();
    if(level1.isNotEmpty){
      level1Select = level1.first.planned??'';
    }
    updateLevel2Address();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Get.back();
      },
      child: Scaffold(
        backgroundColor: Colors.transparent,
        body: GestureDetector(
          onTap: (){

          },
          child: Center(
            child: Container(
              height: 504,
              alignment: Alignment.topCenter,
              width: 311,
              margin: const EdgeInsets.symmetric(horizontal: 32),
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/address/ic_address_dialog_bg.png'),
                ),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    margin: const EdgeInsets.only(top: 18, bottom: 10),
                    child: Text(
                      FMLanguageTool.getText("Please select a address"),
                      style: const TextStyle(color: Color(0xFF333333), fontSize: 20),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      onChooseClick(FMSelectAddressEnum.level1, level1Select);
                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 18, bottom: 10),
                      child: generateChooseText(
                          FMSelectAddressEnum.level1,
                          _selectAddressEnum,
                          level1Select.isEmpty ? '' : level1Select),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      onChooseClick(FMSelectAddressEnum.level2, level2Select);
                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 6, bottom: 10),
                      child: generateChooseText(
                          FMSelectAddressEnum.level2,
                          _selectAddressEnum,
                          level2Select.isEmpty ? '' : level2Select),
                    ),
                  ),
                  Container(
                      margin: const EdgeInsets.symmetric(horizontal: 26),
                      child: Image.asset('assets/address/ic_address_dash.png')),
                  SizedBox(
                      height: 184,
                      child: ListView.builder(
                          itemCount: getAddressList().length,
                          padding: EdgeInsets.zero,
                          physics: const BouncingScrollPhysics(),
                          itemBuilder: (context, index) {
                            List<FMAddressMySelfEntity> mList = getAddressList();
                            final FMAddressMySelfEntity address = mList[index];
                            if (address.planned == getAddressText()) {
                              return Container(
                                height: 40,
                                alignment: Alignment.center,
                                margin: const EdgeInsets.only(
                                    top: 16, left: 26, right: 26),
                                decoration: const BoxDecoration(
                                  color: Color(0xFFFF8800),
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(20)),
                                ),
                                child: Text(
                                  address.planned??'',
                                  style: const TextStyle(
                                      color: Color(0xFFFFFFFF), fontSize: 14),
                                ),
                              );
                            }
                            return GestureDetector(
                              behavior: HitTestBehavior.opaque,
                              onTap: () {
                                setAddressText(address.planned??'');
                                notify();
                              },
                              child: Container(
                                  alignment: Alignment.center,
                                  margin:
                                      const EdgeInsets.only(top: 16, bottom: 10),
                                  child: Text(
                                    address.planned??'',
                                    style: const TextStyle(
                                        color: Color(0xFF333333), fontSize: 14),
                                  )),
                            );
                          })),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      widget.callBack("$level1Select|$level2Select");
                      Get.back();
                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 40, left: 20, right: 20),
                      height: 47,
                      width: double.infinity,
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        color: Color(0xFF000000),
                        borderRadius: BorderRadius.all(Radius.circular(8)),
                        image: DecorationImage(
                          image: AssetImage('assets/address/ic_address_arrow.png'),
                        ),
                      ),
                      child: Text(
                        FMLanguageTool.getText('Confirm'),
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: (){
                      Get.back();
                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        FMLanguageTool.getText('Cancel'),
                        style: const TextStyle(
                          color: Color(0xFF333333),
                          fontSize: 16,
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget generateChooseText(FMSelectAddressEnum currentEnum,
      FMSelectAddressEnum targetEnum, String text) {
    return Text(
      text,
      style: TextStyle(
          color: Color(currentEnum == targetEnum ? 0xFF158F05 : 0xFF999999),
          fontSize: 16),
    );
  }

  void onChooseClick(FMSelectAddressEnum level, String addressKey) {
    if(_selectAddressEnum == FMSelectAddressEnum.level1){
      _selectAddressEnum = level;
    }else if(_selectAddressEnum == FMSelectAddressEnum.level2 && level1Select.isNotEmpty){
      _selectAddressEnum = level;
    }
    notify();
  }

  String getAddressText(){
    if(_selectAddressEnum == FMSelectAddressEnum.level1){
      return level1Select;
    }else if(_selectAddressEnum == FMSelectAddressEnum.level2){
      return level2Select;
    }
    return '';
  }

  void setAddressText(String address){
    if(_selectAddressEnum == FMSelectAddressEnum.level1){
      level1Select = address;
      updateLevel2Address();
    }else if(_selectAddressEnum == FMSelectAddressEnum.level2){
      level2Select = address;
    }
  }

  List<FMAddressMySelfEntity> getAddressList(){
    if(_selectAddressEnum == FMSelectAddressEnum.level1){
      return level1;
    }else if(_selectAddressEnum == FMSelectAddressEnum.level2){
      return level2[level1Select]??[];
    }
    return [];
  }

  void updateLevel2Address(){
    List<FMAddressMySelfEntity> cities = level2[level1Select]??[];
    if(cities.isNotEmpty){
      level2Select = cities.first.planned??'';
    }
  }


  void notify() {
    if (mounted) {
      setState(() {});
    }
  }
}
